<?php 
namespace App\Http\Controllers\TongGaoApi;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use App\Models\Mysql\tonggao\term;

use Excel;
use App\Http\Controllers\TongGaoApi\ExcelActionController;
use App\Http\Controllers\TongGaoApi\WordActionController;

class Dedicated1Controller extends Controller
{	
	const ROUTE_PREFIX = '/api/*';
	protected $request;
	protected $curTime;
	protected $debug;
	/*
	参考文档
	1、https://www.jianshu.com/p/84ef90964304
	2、https://laravel-excel.maatwebsite.nl/docs/3.0/getting-started/basics
	*/

	public function convStarDict(){
		set_time_limit(0);
		term::select("delete from term_info_converted");
		//$columns = term::select("show columns from term_info_converted");
		$columns = term::select("select * from INFORMATION_SCHEMA.Columns where table_name='term_info_converted'");
		
		$dics = array(); $dicIndex=0;
		foreach($columns as $column){
			if ($column->COLUMN_NAME=="chinese_key")
				continue;
			$dics[$column->COLUMN_COMMENT]=$column->COLUMN_NAME;
		}
		var_dump($dics);
		$terms = term::select("select id, chinese_key from term");

		foreach($terms as $term){
			$term_infos = term::select("select * from term_info where term_id={$term->id}");
			if (empty($term_infos))
				continue;
			$fieldArray = array("chinese_key");
			$valueArray = array("\"".trim($term->chinese_key)."\"");
			foreach($term_infos as $term_info){
				$fieldName = $dics[$term_info->source];
				$fieldArray []= "`$fieldName`";
				$valueArray []= "\"".addslashes($term_info->info)."\"";
			}
			$fieldClause = "(".implode(",",$fieldArray).")";
			$valueClause = "(".implode(",",$valueArray).")";
			$insertSql = "INSERT into term_info_converted $fieldClause VALUES $valueClause";
			term::select($insertSql);
			echo "{$term->id}</br>";
			//echo "$insertSql</br>";exit;
		}
	}
	
	public function exportTermInfo(){
		$debug1 = true;
		$debug2 = true;
		
		$englishOption = false;
		$chineseOption = false;
		//$usingOptions = array("DDB01");
		//$usingOptions = array("lamrim");
		//$usingOptions = array("wj4-6");
		$usingOptions = array("foguang2");//lamrim");//ddb01");
		//$dics = array("Soothill-2003-by Longquan","Princeton 2014 Chinese-English by longquan","朗道汉英字典5.0","三藏法数","法相辞典","陈义孝佛学常见辞汇","FoGuangDaCiDian","佛学大辞典","WeiShiMingCiBaiHuaXinJie");	
		$engSources = array("Princeton","Soothill","朗道汉英字典5.0");
		$chnSources = array("三藏法数","法相辞典","陈义孝佛学常见辞汇","佛学大辞典","唯识名词白话新解");
		
		$allChineseKeyArray=array("戒律","大乘","四分律","清净","持戒","功德","出家人","因缘","解脱","信心","大师","方便","三宝","僧团","忏悔","相应","善知识","妄语","次第","正法","精进","境界","善法","成佛","发心","涅槃","智慧","生死","声闻","弟子","无常","瑜伽","律师","增上","如来","菩提道","习气","瑜伽师地论","对治","无量","圆满","思维","世俗","大智","知见","道次","和合","律仪","四分律删繁补阙行事钞","戒相","恭敬","广论","身心","恶业","无上","菩提道次第广论","受戒","毗尼","戒体","学戒","优婆塞","分别","大智度论","羯磨","下品","思惟","利他","道宣","资粮","慈悲","正见","杀生","世尊","戒本","具足","观察","出世","行者","究竟","安乐","善根","业障","功夫","行持","受持","住持","供养","法师","法师","福德","缘起","在世","小乘","法相","法相","行善","依止","邪见","布施","自利","悲心","居士","观念","同行","达磨","五戒","道场","懈怠","正知","戒法","犯戒","般若","护持","出离","凡夫","不善","善友","誓愿","邪淫","业道","佛菩萨","庄严","调伏","善业","大德","差别");
		$allDateStr="精进工作坊-round01-";
		//$countPerRound = 63;
		$countPerRound = 100;
		//for($round=0;$round<ceil(count($allChineseKeyArray)/$countPerRound);$round++){
		//for($round=0;$round<1;$round++){	
		for($round=0;$round<1;$round++){	
			$dateStr="$allDateStr-$round";//"0419";
			$chineseKeyArray = array_slice($allChineseKeyArray,$round*$countPerRound,$countPerRound);
			
			//$chineseKeyArray=array("菩萨","菩提","烦恼","如是","法门","在家","比丘","大乘","清净","持戒","功德","解脱","信心","大师","方便","忏悔","相应","善知识","妄语","次第","正法","精进","善法","成佛","发心","涅槃","智慧","生死","声闻","弟子","无常","律师","增上","菩提道","瑜伽师地论","对治","无量","圆满","世俗","大智","知见","道次","菩提心","恭敬","身心","恶业","无上","菩提道次第广论","受戒","学戒","下品","思惟","利他","资粮","慈悲","正见","杀生","观察","出世","行者",);//"究竟","安乐","善根","业障","受持","住持","法师","法师","福德","缘起","小乘","法相","法相","行善","依止","邪见","布施","自利","悲心","同行","道场","懈怠","正知","戒法","犯戒","般若","护持","出离","凡夫","不善","善友","誓愿","愿力","业道","佛菩萨","庄严","调伏","善业","大德","差别");	//"希求","善巧","我执","法执","愿力","参学","四弃","波罗夷","僧残","二不定法","性戒","遮戒","止持","作持","结戒","结僧戒","受戒","持戒","说戒","安居","自恣","波逸提","舍堕","尼萨耆波逸提");
			
			$cellData = [];
			if ($englishOption){
				$cellData = [];
				foreach($chineseKeyArray as $k=>$chineseKey){
					$cellData[$k][0]=$chineseKey;
					
					$english=$chinese=array();
					foreach($engSources as $source){
						$mandatory = ($source=="Princeton")? true: false;
						$result = $this::getStarDictByChineseKeySource($chineseKey,$source,$mandatory);
						if (!empty($result))
							$english []= str_replace("[dd]","\r\n",$result);
					}
					$cellData[$k][1]=implode("\r\n",$english);
				}
				ExcelActionController::exportExcel(iconv('UTF-8', 'GBK', $dateStr.'StarDict-Eng'),$cellData);
				if ($debug1)	"echo Eng done</br>";
			}
			
			if ($chineseOption){
				$cellData = [];
				foreach($chineseKeyArray as $k=>$chineseKey){
					$cellData[$k][0]=$chineseKey;
					
					foreach($chnSources as $source){
						$mandatory = false;
						$result = $this::getStarDictByChineseKeySource($chineseKey,$source,$mandatory);
						if (!empty($result))
							$chinese []= str_replace("[dd]","\r\n",$result);
					}
					$cellData[$k][1]=implode("\r\n",$chinese);
				}
				ExcelActionController::exportExcel(iconv('UTF-8', 'GBK', $dateStr.'StarDict-Chn'),$cellData);
			}
			
			foreach($usingOptions as $i=>$option){
				$cellData = [];
				foreach($chineseKeyArray as $j=>$chineseKey){
					$cellData[$j][0]=$chineseKey;
					if ($option=="DDB01"){
						//echo "select info from term_info,term where term_info.term_id=term.id and chinese_key=\"$chineseKey\" and term_info.source=\"$option\"</br>";
						//$curInfo=term::select("select info from term_info,term where term_info.term_id=term.id and chinese_key=\"$chineseKey\" and term_info.source=\"$option\"");
						//var_dump($curInfo);
						//$cellData[$j][1]= (!empty($curInfo)) ? str_replace("[b]","\r\n",$curInfo[0]->info) : "";
						$curInfo=term::select("select english info from term_raw_ddb where chinese_key=\"$chineseKey\" ");
						$cellData[$j][1]= (!empty($curInfo)) ? str_replace("[b]","\r\n",$curInfo[0]->info) : "";
					}
					
					if (in_array($option,array("lamrim","wj4-6") )){
						switch($option){
							case "lamrim":
								$articleSql="article_id=56";
								break;
							case "wj4-6":
								$articleSql="article_id between 4 and 55";
								break;
						}
						$curResults = term::select(
							"select term_detail.english,count(*) count from term_detail,term where term.id=term_detail.term_id and chinese_key=\"$chineseKey\" and $articleSql and length(term_detail.english)>0 and term_detail.english is not null group by term_detail.english order by count desc"
						);
						$englishCountArray=array();
						foreach($curResults as $curResult){
							$englishCountArray []= "{$curResult->english} : {$curResult->count}";
						}
						$cellData[$j][1] = (!empty($englishCountArray)) ? implode("\r\n",$englishCountArray) : "";
						//if ($debug1)	echo "$option $chineseKey = {$cellData[$j][1]}";
					}
					
					if ($option=="foguang2"){
						//echo "select info from term_info,term where term_info.term_id=term.id and chinese_key=\"$chineseKey\" and term_info.source=\"$option\"</br>";
						$curInfo=term::select("select info from term_raw_foguang2 where chinese_key=\"$chineseKey\" ");
						//var_dump($curInfo);
						$cellData[$j][1]= (!empty($curInfo)) ? str_replace("[b]","\r\n",$curInfo[0]->info) : "";
					}
					
				}
				ExcelActionController::exportExcel(iconv('UTF-8', 'GBK', $dateStr.'TermInfo'."-$option"),$cellData);
				if ($debug1) echo "$option is done</br>";
			}
		}
    }
	
	public function getStarDictByChineseKeySource($chineseKey, $source,$mandatory=false){
		$sqlPart = "select term_info.info from term_info,term where term.id=term_info.term_id and chinese_key=\"$chineseKey\" and term_info.source=\"$source\"";
		$temp_r=term::select("$sqlPart");
		$result="";
		if (empty($temp_r)){
			if ($mandatory)
				$result="【{$source}】无";
		}else{
			$temp_r[0]->info = str_replace("[dd]","\r\n",$temp_r[0]->info);
			$result="【{$source}】{$temp_r[0]->info}";
		}
		return $result;
	}
	
	public function refExcelToWord(){
		$bookNo = 7;
		$inputFileName = ($bookNo==7)?"第7册引文-20180320.xlsx":"第八册引文-20180320.xlsx";
		$inputRealPath = iconv('UTF-8','GB2312',"F:\\000_booktran\\combine\\引文\\$inputFileName");		
		$cellData = [];
		$sheetIndex = ($bookNo==7)?2:0;

		Excel::load($inputRealPath, function($reader) use (&$cellData,$sheetIndex) {
			$reader = $reader->getSheet($sheetIndex);
			$cellData = $reader->toArray();
	    });
		//var_dump($cellData);
		
		if ($bookNo==7){
			$outputDir = iconv('UTF-8','GB2312',"F:\\000_booktran\\combine\\引文\\现成引文_book7\\");
			$peNoColNo = 1;
			$articleNameColNo = 3;		
			$hasGoodTranslationColNo = 4;
			$translationColNo = 5;
			$chineseBookNameColNo = 6;
			$originalChineseColNo = 8;
		}else{
			$outputDir = iconv('UTF-8','GB2312',"F:\\000_booktran\\combine\\引文\\现成引文_book8\\");
			$peNoColNo = 0;
			$hasGoodTranslationColNo = 1;
			$translationColNo = 3;
			$originalChineseColNo = 2;
		}
		foreach($cellData as $i=>$rowData){
			$peNo = trim($rowData[$peNoColNo]);
			$hasGoodTranslation = trim($rowData[$hasGoodTranslationColNo]);
			$translation = trim($rowData[$translationColNo]);
			$originalChinese = trim($rowData[$originalChineseColNo]);

			if ($bookNo==7){
				$articleName = trim($rowData[$articleNameColNo]);
				$chineseBookName = trim($rowData[$chineseBookNameColNo]);
			}
			
			if ($hasGoodTranslation =="有可靠译文"){
				//echo "$peNo $articleName $chineseBookName</br>";
				$peNoArray = explode(".",$peNo);
				$emptyTranslationFlag = (empty($translation)) ? "空" : "";
				if ($bookNo==7){
					$newPeNo = sprintf("%s.%03d",$peNoArray[0],$peNoArray[1]);
					$chineseBookName = preg_replace("/《|》|·/","",$chineseBookName);
					//echo "$newPeNo</br>";
					//book7_XX-X_A1.094_B-X_ZLL
					//book7_XX-X_A1.094_COPY_$chineseBookName
					$wordFileName = sprintf("book7_XX-X_%s_COPY_%s_%s.docx",$newPeNo,$emptyTranslationFlag,$chineseBookName);
				}else{
					$newPeNo = sprintf("%s.%02d",$peNoArray[0],$peNoArray[1]);
					$wordFileName = sprintf("book8_%s_COPY_%s.docx",$newPeNo,$emptyTranslationFlag);
				}
				echo "$wordFileName</br>";
				$outputRealPath = $outputDir.iconv('UTF-8','GB2312',$wordFileName);
				//echo "$inputRealPath</br>";
				//$text = implode("\r\n\r\n",array($peNo,$originalChinese,$translation));
				$text = array($peNo,$originalChinese,$translation);
				WordActionController::exportWord_01($outputRealPath,$text);
			}
		}
	}
	
/*
	public function excelToTable(){
		//$inputFileName = ($bookNo==7)?"第7册引文-20180320.xlsx":"第八册引文-20180320.xlsx";
		$inputRealPath = iconv('UTF-8','GB2312',"F:\\000_booktran\\combine\\引文\\$inputFileName");	
		$tableName = "jjgzf_01";
		$sheetIndex = 0;
		$excelHasHeader = 1;
		
		$cellData = [];
		Excel::load($inputRealPath, function($reader) use (&$cellData,$sheetIndex) {
			$reader = $reader->getSheet($sheetIndex);
			$cellData = $reader->toArray();
		});
		
		$colCnt = count($cellData,2);
		$fieldNameArray = array("seq_no","chinese_key","freq_grade","proposal","adopted","";
		for($colIndex=0;$colIndex<$colCnt;$colIndex++){
			$fieldNameArray[$colIndex] = sprintf("%03u",$colIndex);
			if ($excelHasHeader){
				if (!empty($cellData[0][$colIndex])){
					if toupper $cellData[0][$colIndex]
				}
			}
		}
		
		term::select("DROP TABLE IF EXISTS `$tableName`");
		term::select("CREATE TABLE `$tableName` (
			`id` int(10) UNSIGNED NOT NULL,
			`seq_no` int(8) UNSIGNED ,
			`chinese_key` varchar(60) ,
			`freq_grade` varchar(10),
			`proposal` varchar(1000),
			`adopted` varchar(1000),
			`comment` text,
			`lamrim` text,
			`dic_english` text,
			`ddb` text,
			`current_article` text,
			`sanskrit` text,
			`pali` text,
			`foguang2` text,
			`dic_chinese` text,
			`article_456` text
		) ENGINE=MYISAM DEFAULT CHARSET=utf8");
		term::select("ALTER TABLE `$tableName`  ADD PRIMARY KEY (`id`)");
		term::select("ALTER TABLE `$tableName`  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT");
		term::select("ALTER TABLE `$tableName` ADD INDEX(` chinese_key `);
*/		
	public function delDupFromFile(){
		set_time_limit(0);
		//$fileName1=iconv('UTF-8', 'GBK', "F:\\000_booktran\\数据准备\\广论phase2\\待查找术语-0621.txt");
		//$fileName1=iconv('UTF-8', 'GBK', "F:\\000_booktran\\数据准备\\广论phase2\\待查找术语-0621.txt");
		$fileName1=iconv('UTF-8', 'GBK', "F:\\000_booktran\\术语讨论会\\石墨\\石墨_0626_export.txt");
		$fileName2=iconv('UTF-8', 'GBK', "F:\\000_booktran\\数据准备\\广论phase2\\中间文件\\已讨论术语总表-0621.txt");
		$file1=file_get_contents($fileName1);
		$itemArray1=explode("\r\n",$file1);
		$file2=file_get_contents($fileName2);
		$itemArray2=explode("\r\n",$file2);
		$dupArray = array();
		foreach($itemArray1 as $item1){
			$found=false;
			foreach($itemArray2 as $item2){
				if ($item1===$item2){
					$found=true;
					$dupArray []=$item1;
					break;
				}
			}
			if (!$found){
				echo "$item1</br>";
			}
		}
		
		echo "duplicated=======================</br>";
		foreach($dupArray as $dupItem){
			echo "$dupItem</br>";
		}
	}
	
	public function detectWordFromFile(){
		set_time_limit(0);
		$fileName1=iconv('UTF-8', 'GBK', "F:\\000_booktran\\combine\\合并\\8-02-1\\0629术语替换-part5\\预处理\\审定术语表-0625.txt");
		$fileName2=iconv('UTF-8', 'GBK', "F:\\000_booktran\\combine\\合并\\8-02-1\\0629术语替换-part5\\预处理\\第八册Chap02-1-0629-part5.txt");
		$file1=file_get_contents($fileName1);
		$itemArray1=explode("\r\n",$file1);
		$file2=file_get_contents($fileName2);
		//$wordArray = array();
		foreach($itemArray1 as $item1){
			if (empty($item1))
				continue;
			if (mb_strpos($file2,$item1)!==false)
				echo "$item1</br>";
		}
	}

}
?>